package com.yao.busi.qiniu;

import android.content.Context;
import android.util.Log;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.Volley;
import com.qiniu.android.http.ResponseInfo;
import com.qiniu.android.storage.UpCompletionHandler;
import com.qiniu.android.storage.UploadManager;
import com.yao.sdk.net.NetConstant;
import com.yao.sdk.net.volley.CookieRequest;
import com.yao.sdk.util.Utils;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2015/11/19.
 */
public class QiNiuUploadTask {

    boolean isUploading = false;

    int okNum;
    int okCount;
    int count;

    private Context context;
    RequestQueue requestQueue;
    UploadStatusListener uploadNotify;
    ArrayList<ImageModel> imageModelList =  new ArrayList<>();

    public QiNiuUploadTask(Context context) {
        this.context = context;
        requestQueue = Volley.newRequestQueue(context);
    }

    public void start(int imageUploadCode, final List<ImageModel> imageModelList, UploadStatusListener uploadNotify) {
        if (uploadNotify == null) {
            throw new NullPointerException("UploadStatusListener should not be null");
        }
        this.uploadNotify = uploadNotify;
        String url = NetConstant.URL_UPLOAD_IMAGE_REQUEST;
        Map<String, String> params = new HashMap<>();
        params.put(NetConstant.KEY_IMAGE_UPLOAD_CODE, imageUploadCode + "");
        Log.d("test", "requestUrl--->" + url);
        CookieRequest cookieRequest = new CookieRequest(Request.Method.POST, url, new CookieRequest.CookieListener() {
            @Override
            public void onSuccess(CookieRequest.ResultSet resultSet) {
                Log.d("qiniu", "start()-->" + resultSet.responseInfo);
                try {
                    JSONObject jsonObject = new JSONObject(resultSet.responseInfo);
                    String imageFilter = jsonObject.getJSONObject(NetConstant.KEY_DATA).getString(NetConstant.KEY_IMAGE_FILTER);
                    String token = jsonObject.getJSONObject(NetConstant.KEY_DATA).getString(NetConstant.KEY_TOKEN);
                    upload(imageFilter, token, imageModelList);

                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Log.d("qiniu", "error--");

                    QiNiuUploadTask.this.uploadNotify.onError(error.toString());

            }
        });
        cookieRequest.setParam(params);
        requestQueue.add(cookieRequest);
        requestQueue.start();
    }

    private void upload(String imageUrlPrefix, String token, final List<ImageModel> imageModelList) {
        Log.d("qiniu", "upload()-1->");

        if (isUploading) {
            return;
        }
        try {
            if (!Utils.isEmpty(imageModelList)) {
                Log.d("qiniu", "upload()-2->");

                isUploading = true;
                count = 0;
                okCount = 0;
                okNum = imageModelList.size();

                UploadManager uploadManager = new UploadManager();

                for (int i = 0; i < imageModelList.size(); i++) {
                    Log.i("qiniu", "cur Index -->" + i);
                    final String url = imageModelList.get(i).originalUrl;
                    String tmpKey = imageUrlPrefix + "_" + i;
                    final ImageModel imageModel = imageModelList.get(i);
                    uploadManager.put(url, tmpKey, token,
                            new UpCompletionHandler() {
                                @Override
                                public void complete(String key, ResponseInfo info, JSONObject res) {
                                    Log.d("qiniu", key + ",\r\n " + info + ",\r\n " + res);
                                    count++;
                                    imageModel.generatedUrl = key;
                                    if (info.isOK()) {
                                        // 图片上传成功
                                        imageModel.isOk = true;
                                        okCount++;
                                    } else {
                                        Log.e("qiniu", key + " upload failed");
                                        imageModel.isOk = false;
                                    }
                                    uploadNotify.onNotify(imageModel);
                                    if (count == okNum) {
                                        if (okCount == okNum) {
                                            uploadNotify.onAllCompleted(imageModelList, true);
                                        } else {
                                            uploadNotify.onAllCompleted(imageModelList, false);

                                        }

                                    }

                                }
                            }, null);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            isUploading = false;
        }

    }


}
